package validate;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Validate
 */
@WebServlet("/Validate")
public class Validate extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Validate() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Color getColor(int s, int c) {
		if (s > 255)
			s = 255;
		if (c > 255)
			c = 255;
		Random random = new Random();
		int r = s + random.nextInt(c - s);
		int g = s + random.nextInt(c - s);
		int b = s + random.nextInt(c - s);
		return new Color(r, g, b);
	}

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/**
		 * 图片相关设置
		 */
		response.setHeader("param", "no-cache");
		response.setHeader("cache-contrl", "no-cache");
		response.setDateHeader("respires", 0);
		response.setContentType("image/jpeg");
		/**
		 * 图片高度
		 */
		int width = 86;
		/**
		 * 涂片宽度
		 */
		int height = 22;

		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		/**
		 * 获得画笔
		 */
		Graphics g = bufferedImage.getGraphics();
		Graphics2D gd = (Graphics2D) g;

		g.setColor(getColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("楷体", Font.BOLD, 18));
		g.setColor(getColor(180, 200));

		Random random = new Random();

		/**
		 * 画线条
		 */
		for (int i = 0; i < 100; i++) {
			BasicStroke basicStroke = new BasicStroke(2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL);
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int x1 = random.nextInt(6) - 1;
			int y1 = random.nextInt(12) - 1;
			Line2D ld = new Line2D.Double(x, y, x + x1, y + y1);
			gd.setStroke(basicStroke);
			gd.draw(ld);
		}

		String s = "";
		String c = "";
		for (int i = 0; i < 4; i++) {
			c = String.valueOf((char)(random.nextInt(26)+65));
			s = s + c;
			System.out.println(c);
			Color color = new Color(20+random.nextInt(110), 20+random.nextInt(110), random.nextInt(110));
			g.setColor(color);
			g.drawString(c, 15*i+18, 14+random.nextInt(5));
		}

		HttpSession session = request.getSession(true);
		session.setAttribute("code", s);
		g.dispose();
		ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());

	}

}
